const fs = require("fs");
var path = require("path");
var glob = require("glob");

/* 一些工具function */
// 读取文件
function read(path) {
	return fs.readFileSync(path, "utf8");
}
// 判断是否未定义
function isDef(target) {
	return target !== undefined;
}
// 判断是否是数组
function isArray(obj) {
	return Object.prototype.toString.call(obj) === "[object Array]";
}
/*
    正式的代码↓
 */

module.exports = function createConfig(isCover) {
	// 获取vcv的配置
	let packageJSON = read(path.resolve("./", "./package.json"));
	let vcvConfig = JSON.parse(packageJSON).vcvConfig;

	if (!isDef(vcvConfig)) {
		console.log("请配置vcvConfig");
		return;
	}
	// 生成路由名称，用于分离组件
	let routeNames = new Map();
	let generateRouteNames = (rpath = "") => {
		// 获取路由路径
		// let routerPath = path.join(__dirname, rpath);
		let routerPath = path.resolve("./", rpath);
		let routerFile = read(routerPath);
		// 找到 { component: XXX } 这种结构的组件 如果改名的不排除
		let normalCompMatch = routerFile.match(/component\:(\s*\w*\,*)/g);
		normalCompMatch &&
			normalCompMatch.map((item) => {
				let compName = item.replace(/["'\s]/g, "").split(":")[1] || "";
				if (compName) {
					routeNames.set(compName, {
						type: "Name",
					});
				}
			});
		// 获取import进来的组件，用于比对路由引入时改名
		let importReg =
			/import\s*\w{1,}\s*from\s*[\'|\"][\/|\.|\w]{1,}\/(\w{1,})/g;
		let importAliasMap = new Map();
		let importMatch = routerFile.match(importReg);
		importMatch &&
			importMatch.map((item) => {
				let importName = item.match(/\s*(\w{1,})\s*from/)[1];
				let fromName = item.match(/[\'|\"][\/|\.|\w]{1,}\/(\w{1,})/)[1];
				importAliasMap.set(importName, fromName);
				// console.log('im',importName, fromName)
			});
		routeNames.forEach((val, key) => {
			if (importAliasMap.has(key)) {
				routeNames.set(importAliasMap.get(key), {
					type: "Name",
					alias: key,
				});
				routeNames.delete(key);
			}
		});
		// console.log(routerFile.match(importReg))
		// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
		// 获取路由懒加载过来的组件
		let compImportReg = /component\:\s*.{1,}\/\w{1,}(\.vue)*(\'|\")\)/g;
		// console.log(routerFile.match(compImportReg))
		compImportMatch = routerFile.match(compImportReg);
		compImportMatch &&
			compImportMatch.map((item) => {
				let compName = item.match(/\/(\w{1,})(\.vue){0,1}[\'\"]\)/)[1];
				routeNames.set(compName, {
					type: "import",
					value: item,
				});
			});
	};

	// 查找路由文件
	function findRouterPath(routerFile) {
		try {
			return glob.sync(routerFile, {}) || [];
		} catch (err) {
			console.log("vcvConfig.routerPath有误：", err);
			return [];
		}
	}
	// 获取路由配置，排除路由的引入文件
	let routerPaths = [];
	if (typeof vcvConfig.routerPath === "string") {
		routerPaths = routerPaths.concat(findRouterPath(vcvConfig.routerPath));
	} else if (isArray(vcvConfig.routerPath)) {
		vcvConfig.routerPath.forEach((rpath) => {
			routerPaths = routerPaths.concat(findRouterPath(rpath));
		});
	} else {
		console.log("不知道传入的vcvconfig routerPath格式,按空处理");
	}
	// 遍历文件查找page页面
	routerPaths.forEach((rpath) => {
		generateRouteNames(rpath);
	});

	// 获取待搜索的查找范围
	let globOps = {
		ignore: ["src/vcv/*"],
	};
	let allVueFiles = [];
	function findVue(path) {
		try {
			return glob.sync(path, globOps) || [];
		} catch (err) {
			console.log("vcvConfig.include有误：", err);
			return [];
		}
	}
	// allVueFiles = glob.sync("src/**/*.vue", globOps) || []

	if (typeof vcvConfig.include === "string") {
		allVueFiles = findVue(vcvConfig.include);
	} else if (isArray(vcvConfig.include)) {
		vcvConfig.include.forEach((filePath) => {
			let tempFiles = findVue(filePath);
			allVueFiles = allVueFiles.concat(tempFiles);
		});
	} else {
		allVueFiles = findVue("src/**/**/*.vue");
	}

	//排除页面组件
	let allComponents = [];
	for (let i = 0, len = allVueFiles.length; i < len; i++) {
		let file = allVueFiles[i];
		let fileName = file.match(/(\w{1,}).vue/)[1];
		if (fileName === "App") {
			continue;
		}
		if (!routeNames.has(fileName)) {
			allComponents.push({
				fileName: fileName,
				originPath: file,
				path: file.replace(/.*src\//, "./"),
			});
		}
	}
	// console.log('allComponents',allComponents)
	let compsText = "";
	allComponents.length &&
		allComponents.forEach((item) => {
			compsText += `{
        component: ()=> import('${item.path}'),
        desc: '${item.fileName}组件的说明在这里',
        name: '${item.fileName}',
        path: '${item.path}'
    },`;
		});
	let text = `
const componentsList = [
    ${compsText}
]

export default {
    content: componentsList,
    view: ()=> import('./vcv/Page.vue')
}
`;
	if (isCover) {
		fs.writeFileSync("./src/vcv.config.js", text);
	} else {
		fs.writeFileSync(`./src/vcv.config.${new Date().getTime()}.js`, text);
	}
};
